# -*- coding: utf-8 -*-
"""
Created on Tue Oct 31 14:47:56 2017
计算分类准确率（研究院）
(there are some differences about "sorted" function and judge element in a dict 
between python2.x and python3.x,this is a correct version witch can run in python3.x)
@author: aia_zxl
"""

'''读入valid文件，生成字典'''
def generate_valid_dictionary(filename):
	valid_dict={}
	img_num = 0
	filelines = open(filename).readlines()
	for line in filelines:
		ret_set = line.strip().split()
		
		img_id = ret_set[0]
		class_score = float(ret_set[6])
		if img_id not in valid_dict:
			valid_dict[img_id]=class_score
			img_num = img_num + 1
	print("valid img_num:",img_num)
	return valid_dict

''' 读入check_normal文件，生成字典'''
def generate_label_dictionary(filename):
	label_dict={}
	img_num = 0
	filelines = open(filename).readlines()
	for line in filelines:
		ret = line.strip().split()
		class_label = float(ret[0])
		fl_nm = ret[1].split('.')[0]
		label_dict[fl_nm] = class_label
		img_num = img_num + 1
	print("total img_num:",img_num)
	return label_dict

def calc_classification_accuracy(valid_dict,label_dict):
	accu_num = 0 #z准确率
	ft = 0 #假正率（即本身为不干预1,检测为干预0）
	fn = 0 #假负率（即本身为干预0,检测为不干预1）
	for key in valid_dict:
		if (valid_dict[key]>0.5 and label_dict[key]>0.5) or (valid_dict[key]<0.5 and label_dict[key]<0.5):
			accu_num = accu_num + 1
		else:
			print(key,"  label:",label_dict[key],"  pred:",valid_dict[key])
			if valid_dict[key]<0.5 and label_dict[key]>0.5:
				ft = ft + 1
			else:
				fn = fn + 1   
	return accu_num/len(valid_dict),ft/len(valid_dict),fn/len(valid_dict)


def main():
	valid_file = "/home/aia2/workspace/zxl/works/yolo_institute/results/comp4_det_test_wheel.txt"
	check_normal_file = "/media/aia2/538b3ffa-f394-4e50-bb99-33c5b6db685f/aia2/datasets/institute/voc/Check_normal.txt"
	valid_dict = generate_valid_dictionary(valid_file)
	label_dict = generate_label_dictionary(check_normal_file)
	accuracy,ft,fn = calc_classification_accuracy(valid_dict,label_dict)
	print("accuracy:",accuracy,"  ft:",ft,"  fn:",fn)
	
if __name__ == '__main__':
	main()

